package com.qing.springbootinit.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

// * @author <a href="https://github.com/qingfengzy">qingfengzy</a>

@Component
public class ExcelUtils {
    public  String excelTocsv(MultipartFile multipartFile)  {
//        输入你要读取的excel文件名
        File file = null;
//        try {
////            file = ResourceUtils.getFile("classpath:测试数据.xlsx");
//            list = EasyExcel.read(multipartFile.getInputStream());
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//       用列表的MAP来装
        List<Map<Integer,String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println(list);
        // 如果数据为空
        if(CollectionUtils.isEmpty(list)){
            return "";
        }

        // 转换为 csv
        StringBuilder stringBuilder = new StringBuilder();
        // 读取表头(第一行)
        LinkedHashMap<Integer,String> headerMap= (LinkedHashMap<Integer, String>) list.get(0);
//       然后数据按照逗号分隔
        List<String> headerList = headerMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
//        System.out.println(StringUtils.join(","));
//        给每一行都加一个逗号数据
        stringBuilder.append(StringUtils.join(headerList,",")).append("\n");
        // 读取数据(读取完表头之后，从第一行开始读取)
        for(int i = 1; i<list.size();i++){
            LinkedHashMap<Integer,String> dataMap = (LinkedHashMap<Integer, String>) list.get(i);
//            System.out.println(StringUtils.join(dataMap.values(),","));
            List<String> dataList = dataMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());
            stringBuilder.append(StringUtils.join(dataList,",")).append("\n");
        }
        System.out.println(stringBuilder);
        return stringBuilder.toString();
    }

//    public static void main(String[] args) {
//        excelTocsv(null);
//    }

}
